/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.inspur.edp.ide.config.webapi.service;

import com.fasterxml.jackson.databind.JsonNode;
import com.inspur.edp.ide.config.webapi.common.FileUtil;
import com.inspur.edp.ide.config.webapi.entity.PanelDescription;
import com.inspur.edp.ide.config.webapi.entity.PanelStyle;
import com.inspur.edp.ide.config.webapi.entity.PluginConfig;
import com.inspur.edp.web.common.utility.StringUtility;
import io.iec.edp.caf.common.JSONSerializer;
import io.iec.edp.caf.common.environment.EnvironmentUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.configurationprocessor.json.JSONObject;

import java.io.File;
import java.nio.file.Paths;

/**
 * ide service
 * @author  noah
 */
@Slf4j
public class WebIDEService {
    private static WebIDEService instance;
    private static PluginConfig pluginConfig;

    private WebIDEService() {
        initPluginConfig();
    }

    public static WebIDEService getInstance() {
        if (instance == null) {
            instance = new WebIDEService();
        }
        return instance;
    }

    public final PluginConfig getPluginConfig() {
        this.initPluginConfig();
        return pluginConfig;
    }

    private void initPluginConfig() {
        String devRootPath = EnvironmentUtil.getBasePath();
        String pluginsPath = Paths.get(devRootPath).resolve("web/platform/dev/main/web/webide/plugins".replace('/', File.separatorChar)).toString();
        if (!(new File(pluginsPath)).isDirectory()) {
            return;
        }

        PluginConfig config = new PluginConfig();
        String[] pluginDirs = (new File(pluginsPath)).list((ff, nn) -> ff.isDirectory());

        for (String dir : pluginDirs) {
            String fullPath = Paths.get(pluginsPath, dir).toString();
            PanelDescription panelDescription = getPluginDescription(getPluginPackageJson(fullPath));
            if (panelDescription == null) {
                continue;
            }
            reviseUrlWithDir(panelDescription, dir);
            switch (panelDescription.getStyle()) {
                case Eager:
                    config.getEager().add(panelDescription);
                    break;
                case Lazy:
                    config.getLazy().add(panelDescription);
                    break;
                case Editor:
                    config.getEditor().add(panelDescription);
                    break;
                default:
                    break;
            }
        }
        pluginConfig = config;
    }

    private String getPluginPackageJson(String path) {
        String fullPath = Paths.get(path).resolve("plugin.conf.json").toString();

        if (!(new File(fullPath)).isFile()) {
            return null;
        }
        return FileUtil.readFile(fullPath);
    }

    private PanelDescription getPluginDescription(String jsonStr) {
        if (StringUtility.isNullOrEmpty(jsonStr)) {
            return null;
        }
        try {
            JSONSerializer.deserialize(jsonStr, JSONObject.class);
            JsonNode jobj = JSONSerializer.deserialize(jsonStr, JsonNode.class);
            // 获取插件视图注册信息
            PanelDescription result = jobj.get("panel") == null ? null : JSONSerializer.deserialize(jobj.get("panel").toString(), PanelDescription.class);
            JsonNode activationCommands = jobj.get("activationCommands");
            JsonNode editorDescription = jobj.get("editor");
            if (result != null) {
                if (activationCommands != null) {
                    result.setStyle(PanelStyle.Lazy);
                    result.setActivationCommands(activationCommands);
                } else if (editorDescription != null) {
                    result.setStyle(PanelStyle.Editor);
                    result.setEditor(editorDescription);
                }
            }
            return result;
        } catch (RuntimeException e) {
            log.error(e.getMessage(), e);
            return null;
        }
    }

    /**
     * 修正panelDescription的url路径
     * n版url不带index.html，server会自动跳转，j版server不行。
     * @param panelDescription
     * @param dir
     */
    private void reviseUrlWithDir(PanelDescription panelDescription, String dir) {
        String url = panelDescription.getUrl();
        if (url != null && url.matches(".+(\\.html|\\.htm)(\\?.*)?$")) {
            return;
        }

        // url不符合要求，需要重新指定
        panelDescription.setUrl("/platform/dev/main/web/webide/plugins/" + dir + "/index.html");
    }
}
